package com.xiaxinyu.thread.pool.config;

import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.*;

/**
 * 自定义线程池
 *
 * @author xiaxinyu3
 * @date 2020.2.22
 */
public class CustomThreadPool {
    private volatile static ThreadPoolExecutor executorService;

    private static BlockingQueue<Runnable> queue = null;

    private CustomThreadPool() {
    }

    public static ThreadPoolExecutor get() {
        if (Objects.isNull(executorService)) {
            synchronized (CustomThreadPool.class) {
                if (Objects.isNull(executorService)) {
                    executorService = generate();
                }
            }
        }
        return executorService;
    }

    /**
     * 生成线程池
     *
     * @return 自定义Gitlab线程池
     */
    private static ThreadPoolExecutor generate() {
        //核心线程数
        int poolSize = Runtime.getRuntime().availableProcessors();
        //有界队列深度
        //BlockingQueue<Runnable> queue = new SynchronousQueue<>();

        //有界队列深度
        BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(9999);

        //超过最大线程上限 将任务回馈至发起方比如main线程
        RejectedExecutionHandler policy = new ThreadPoolExecutor.AbortPolicy();
        //创建线程工厂
        CustomThreadFactory customThreadFactory = new CustomThreadFactory();
        return new ThreadPoolExecutor(poolSize, poolSize , 0, TimeUnit.SECONDS, queue, customThreadFactory, policy);
    }
}
